package com.framework.admin.service.impl;

import com.framework.admin.repository.MenuRepository;
import com.framework.admin.repository.ModuleFormFieldRepository;
import com.google.common.collect.Lists;
import com.framework.admin.domain.param.ModuleFormParam;
import com.framework.admin.domain.vo.LoadModuleDataVo;
import com.framework.admin.mapper.ModuleFormFieldMapper;
import com.framework.admin.mapper.ModuleFormMapper;
import com.framework.admin.mapper.ModuleTableFieldMapper;
import com.framework.admin.model.ModuleForm;
import com.framework.admin.model.ModuleFormField;
import com.framework.admin.model.SysMenu;
import com.framework.admin.repository.ModuleFormRepository;
import com.framework.admin.service.IMenuService;
import com.framework.admin.service.IModuleFormService;
import com.framework.common.config.SessionUtil;
import com.framework.common.constant.MenuConstant;
import com.framework.common.exception.BusinessException;
import com.framework.common.util.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Map;


/**
 * @description: 模块表单管理 Service
 * @author: lizurong
 * @version: 1.0
 * @date: 2021-03-08 13:07:55
 */
@Service
public class ModuleFormService implements IModuleFormService {
    @Autowired
    private ModuleFormMapper baseMapper;

    @Autowired
    private ModuleFormRepository baseRepo;

    @Autowired
    private ModuleFormFieldRepository moduleFormFieldRepository;

    @Autowired
    private ModuleFormFieldMapper moduleFormFieldMapper;

    @Autowired
    private ModuleTableFieldMapper moduleTableFieldMapper;

    @Autowired
    private ModuleTableFieldService moduleTableFieldService;

    @Autowired
    private IMenuService iMenuService;

    @Autowired
    private MenuRepository menuRepository;

    @Override
    public Page<ModuleForm> listPage(ModuleFormParam param, PageRequest pageRequest) {
        Page<ModuleForm> page = baseMapper.listPage(param, pageRequest);
        String loginUserComCode = SessionUtil.getCompany().getCode() + "_";
        for (ModuleForm moduleForm : page.getContent()) {
            if (StringUtils.isEmpty(moduleForm.getMenuId())) {
                continue;
            }
            SysMenu sysMenu = menuRepository.findOne(moduleForm.getMenuId());
            if (null == sysMenu) {
                continue;
            }
            moduleForm.setMenuName(sysMenu.getName());
            moduleForm.setMenuCode(sysMenu.getCode().replace(loginUserComCode, ""));
            String tableName = StringUtils.isNotEmpty(moduleForm.getTableName()) ? moduleForm.getTableName().replace(loginUserComCode, "") : "";
            String tableDesc = StringUtils.isNotEmpty(moduleForm.getTableDesc()) ? moduleForm.getTableDesc() : "";
            moduleForm.setTableName(tableName + "(" + tableDesc + ")");
            moduleForm.setPath(sysMenu.getPath());
            moduleForm.setPcode(sysMenu.getPcode());
            moduleForm.setMenuStatus(sysMenu.getHidden() ? "hidden" : "show");
        }
        return page;
    }

    @Override
    public String save(ModuleForm param) {
        String loginUserComCode = SessionUtil.getCompany().getCode() + "_";
        //校验code唯一
        SysMenu dbMenu = menuRepository.getTopByCode(loginUserComCode + param.getMenuCode());
        if (dbMenu != null) {
            throw new BusinessException("菜单编码已存在!请换个编码");
        }
        ModuleForm entity = baseRepo.save(param);
        SysMenu sysMenu = new SysMenu();
        sysMenu.setType("1");
        sysMenu.setCache(false);
        sysMenu.setIcon("java");
        sysMenu.setHidden(true);
        sysMenu.setSort(999);
        sysMenu.setComponent("form/dynamic");
        sysMenu.setName(param.getMenuName());
        sysMenu.setCode(loginUserComCode + param.getMenuCode());
        sysMenu.setPcode(param.getPcode());
        sysMenu.setPath(param.getPath());
        if (StringUtils.isEmpty(sysMenu.getPcode())) {
            sysMenu.setPcode(MenuConstant.ROOT);
        }
        //保存menu表
        iMenuService.save(sysMenu);
        //设置menuId
        entity.setMenuId(sysMenu.getId());
        if (StringUtils.isNotEmpty(param.getTableName())) {
            //选择了自定义表
            String tableName = param.getTableName().substring(0, param.getTableName().indexOf("("));
            String tableDesc = param.getTableName().substring(param.getTableName().indexOf("("), param.getTableName().length() - 1);
            entity.setTableName(tableName);
            entity.setTableDesc(tableDesc);
        }
        return entity.getId();
    }

    @Override
    public void delete(List<String> ids) {
        String[] arr = new String[ids.size()];
        List<String> menuIds = Lists.newArrayList();
        for (String moduleId : ids) {
            ModuleForm moduleForm = baseRepo.findOne(moduleId);
            menuIds.add(moduleForm.getMenuId());
            //删除表单字段表
            moduleFormFieldMapper.delteByModuleFormId(moduleId);
            if (StringUtils.isNotEmpty(moduleForm.getTableName())) {
                //自定义表已创建则同步删除 自定义字段表
                moduleTableFieldMapper.deleteByTableName(moduleForm.getTableName());
                //删除数据库自定义表
                moduleTableFieldService.deleteCustomTable(moduleForm.getTableName());
            }

        }
        //刪除自定义菜单
        iMenuService.delete(menuIds);
        baseRepo.deleteById(ids.toArray(arr));
    }

    @Override
    public void update(ModuleForm param) {
        ModuleForm entity = baseRepo.findOne(param.getId());
        BeanUtils.copyProperties(param, entity, "id");
        //更新
        SysMenu sysMenu = menuRepository.findOne(param.getMenuId());
        if (sysMenu == null) {
            return;
        }
        //校验code唯一
        String companyCode = SessionUtil.getCompany().getCode() + "_";
        String newCode = param.getMenuCode();
        if (!sysMenu.getCode().contains(companyCode)) {
            newCode = companyCode + newCode;
        }
        SysMenu dbMenu = menuRepository.getTopByCode(newCode);
        if (dbMenu != null && !(companyCode + param.getMenuCode()).equals(sysMenu.getCode())) {
            //新的菜单code数据库也有值&&新code和老code不一样
            throw new BusinessException("菜单编码已存在!请换个编码");
        }
        sysMenu.setName(param.getMenuName());
        sysMenu.setCode(newCode);
        sysMenu.setPcode(param.getPcode());
        String path = param.getPath();
        if (path.length() < 34) {
            path = path + "/" + param.getId();
        }
        sysMenu.setPath(path);
        sysMenu.setHidden("hidden".equals(param.getMenuStatus()));
        menuRepository.save(sysMenu);
        if (StringUtils.isNotEmpty(param.getTableName())) {
            //选择了自定义表
            String tableName = param.getTableName().substring(0, param.getTableName().indexOf("("));
            String tableDesc = param.getTableName().substring(param.getTableName().indexOf("("), param.getTableName().length() - 1);
            entity.setTableName(tableName);
            entity.setTableDesc(tableDesc);
        }
        baseRepo.save(entity);
    }

    @Override
    public void updateFormJson(String formJson, String moduleFormId) {
        baseRepo.updateFormJson(formJson, moduleFormId);
    }

    @Override
    public List<String> tableList() {
        String loginUserComCode = SessionUtil.getCompany().getCode() + "_";
        List<Map<String, String>> mapList = baseMapper.tableList(loginUserComCode);
        List<String> tableNameAndDescList = Lists.newArrayList();
        mapList.forEach(map -> {
            tableNameAndDescList.add(map.get("tableName").replace(loginUserComCode, "") + "(" + map.get("tableDesc") + ")");
        });
        return tableNameAndDescList;
    }

    @Override
    public LoadModuleDataVo loadModuleData(String moduleFormId) {
        String loginUserComCode = SessionUtil.getCompany().getCode() + "_";
        LoadModuleDataVo loadModuleDataVo = new LoadModuleDataVo();
        ModuleForm moduleForm = baseRepo.findOne(moduleFormId);
        loadModuleDataVo.setSelectSql(moduleForm.getSelectSql());
        loadModuleDataVo.setInsertSql(moduleForm.getInsertSql());
        loadModuleDataVo.setDeleteSql(moduleForm.getDeleteSql());
        loadModuleDataVo.setUpdateSql(moduleForm.getUpdateSql());
        loadModuleDataVo.setQueryParams(moduleForm.getQueryParams());
        List<ModuleFormField> moduleFormFields = moduleFormFieldRepository.getByModuleFormId(moduleFormId);
        List<ModuleFormField> listFormList = moduleFormFieldRepository.getListFormByModuleFormId(moduleFormId);
        List<ModuleFormField> formList = moduleFormFieldRepository.getFormByModuleFormId(moduleFormId);
        loadModuleDataVo.setModuleFormFieldList(moduleFormFields);
        loadModuleDataVo.setListFormList(listFormList);
        loadModuleDataVo.setFormList(formList);
        loadModuleDataVo.setProcDefName(moduleForm.getProcDefName());
        loadModuleDataVo.setFormJson(moduleForm.getFormJson());
        loadModuleDataVo.setTableName(StringUtils.isNotEmpty(moduleForm.getTableName()) ? moduleForm.getTableName().replace(loginUserComCode, "") : "");
        loadModuleDataVo.setTableDesc(moduleForm.getTableDesc());
        loadModuleDataVo.setModuleName(moduleForm.getModuleName());
        loadModuleDataVo.setFormDesc(moduleForm.getFormDesc());
        return loadModuleDataVo;
    }

}
